from http import HTTPStatus
from dashscope.api_entities.dashscope_response import DashScopeAPIResponse, ImageSynthesisUsage, ImageSynthesisOutput


class APIResponse(DashScopeAPIResponse):
    output: ImageSynthesisOutput
    usage: ImageSynthesisUsage

    @staticmethod
    def from_api_response(api_response: DashScopeAPIResponse):
        """类型转换
        将 DashScopeAPIResponse 转化为 APIResponse
        """
        output = None
        usage = None
        code = api_response.code
        message = api_response.message
        if api_response.status_code == HTTPStatus.OK:
            if api_response.output is not None:
                output = ImageSynthesisOutput(**api_response.output)
                if api_response.output.get("code") is not None:
                    code = output.code
                if api_response.output.get("message") is not None:
                    message = output.message
            if api_response.usage is not None :
                if api_response.usage.get("image_count") is not None:
                    usage = ImageSynthesisUsage(**api_response.usage)
                else:
                    usage = api_response.usage
        return APIResponse(status_code=api_response.status_code,
                           request_id=api_response.request_id,
                           code=code,
                           message=message,
                           output=output,
                           usage=usage)


